package com.avcdata.national.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.avcdata.aoscustommade.R;
import com.avcdata.aoscustommade.activity.Login_Activity;
import com.avcdata.aoscustommade.activity.Main_Activity;
import com.avcdata.aoscustommade.adapter.MyWheelAdapter;
import com.avcdata.aoscustommade.main.BaseActivity;
import com.avcdata.aoscustommade.utils.AppActivityManager;
import com.avcdata.aoscustommade.utils.AvcConstants;
import com.avcdata.aoscustommade.utils.SharedPreferencesUtils;
import com.avcdata.national.adapter.CategorySynthesisAdapter;
import com.avcdata.national.module.CateSyncInfo;
import com.avcdata.national.module.CateSyncListInfo;
import com.avcdata.national.module.UserBrandsInfo;
import com.avcdata.national.module.UserCompetingBrandInfo;
import com.avcdata.national.network.BaseLog;
import com.avcdata.national.network.JsonRunnable;
import com.avcdata.national.network.ThreadPoolUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.wx.wheelview.widget.WheelView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.avcdata.aoscustommade.R.id.dialog_cancel;
import static com.avcdata.aoscustommade.R.id.jiazai_layout;
import static com.avcdata.aoscustommade.R.id.sale_text;

/**
 * NewAOSApp
 * com.avcdata.national.activity
 * Created by lic on 2017/8/17.
 * CSDN http://blog.csdn.net/lucasey
 */

public class NationalOverViewActivity extends BaseActivity {

    @ViewInject(R.id.left_group)
    private LinearLayout left_group;
    @ViewInject(R.id.right_group)
    private LinearLayout right_group;
    @ViewInject(R.id.title)
    private TextView title;

    @ViewInject(R.id.jiazai_layout)
    private LinearLayout loading;

    @ViewInject(R.id.sale_type)
    private LinearLayout sale_type;
    @ViewInject(R.id.sale_text)
    private TextView sale_text;
    @ViewInject(R.id.line_type)
    private LinearLayout line_type;
    @ViewInject(R.id.line_text)
    private TextView line_text;
    @ViewInject(R.id.week_type)
    private LinearLayout week_type;
    @ViewInject(R.id.week_text)
    private TextView week_text;

    @ViewInject(R.id.national_lv)
    private GridView national_lv;

    private Dialog dialog;

    private ArrayList<String> dataMeasure;
    private ArrayList<String> weeks;
    private String measureString = "online";
    private String weekString = "current";
    private String saleString = "amount";
    private String measureStringTemp = "";
    private String weekStringTemp = "";
    private String saleStringTemp = "";
    private ArrayList<String> sales;


    private List<CateGroiseOverview> datas;
    private CategorySynthesisAdapter adapter;

    SharedPreferencesUtils sp ;

    @Override
    public void initView() {
        setContentView(R.layout.activity_national_overview);
        AppActivityManager.getAppManager().addActivity(this);
        ViewUtils.inject(this);
    }

    @Override
    public void initInstall() {
        title.setText("品类综合");
        loading.setVisibility(View.GONE);
        right_group.setVisibility(View.VISIBLE);
        sp = new SharedPreferencesUtils(this);
    }

    @Override
    public void initData() {
        dataMeasure = new ArrayList<>();
        dataMeasure.add("线上");
        dataMeasure.add("线下");
        weeks = new ArrayList<>();
        weeks.add("当前周");
        weeks.add("近四周");
        weeks.add("近八周");
        weeks.add("本年累计");
        sales = new ArrayList<>();
        sales.add("销量");
        sales.add("销额");
        left_group.setOnClickListener(this);
        right_group.setOnClickListener(this);
        line_type.setOnClickListener(this);
        week_type.setOnClickListener(this);
        sale_type.setOnClickListener(this);
        //设置线上线下方式
        if(new SharedPreferencesUtils(this).getLineType() == 1  ){
            line_text.setText("线上");
            measureString = "online";
        }else{
            line_text.setText("线下");
            measureString = "offline";
        }
        //设置销量销额方式
        if(new SharedPreferencesUtils(this).getSaleType() == 1  ){
            sale_text.setText("销量");
            saleString = "volume";
        }else{
            sale_text.setText("销额");
            saleString = "amount";
        }
        //设置周度
        switch (new SharedPreferencesUtils(this).getWeekType()){
            case "近四周":
                week_text.setText("近四周");
                weekString = "fourWeek";
                break;
            case "近八周":
                week_text.setText("近八周");
                weekString = "eightWeek";
                break;
            case "本年累计":
                week_text.setText("本年累计");
                weekString = "year";
                break;
            case "当前周":
                week_text.setText("当前周");
                weekString = "current";
                break;
            default:
                week_text.setText("当前周");
                weekString = "current";
                break;
        }
        datas = new ArrayList<>();
        adapter = new CategorySynthesisAdapter(this,datas);
        national_lv.setAdapter(adapter);
        national_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BaseLog.e("onclick_cate",datas.get(position).getCategory());
                if(null == new SharedPreferencesUtils(NationalOverViewActivity.this).getCompetingBrands(datas.get(position).getCategory())
                        || new SharedPreferencesUtils(NationalOverViewActivity.this).getCompetingBrands(datas.get(position).getCategory()).size() == 0){
                    Intent intent = new Intent(NationalOverViewActivity.this, PersonalAttentionCategoryActivity.class);
                    intent.putExtra("where","login");
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(NationalOverViewActivity.this,ScaleBasisRatioActivity.class);
                    intent.putExtra("cate",datas.get(position).getCategory());
                    startActivity(intent);
                }
            }
        });
        getCompeting();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getCompeting();
        sp.setRatioType(1);
        sp.setSaleType(2);
        sp.setLineType(2);
    }

    @Override
    public void evenControl() {

    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()){
            case R.id.left_group:
                this.finish();
                break;
            case R.id.sale_type:
                showDialogSelect(1);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.line_type:
                showDialogSelect(3);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.week_type:
                showDialogSelect(2);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.right_group:
                showShare ( getWindow ().getDecorView ().findViewById ( android.R.id.content ) );
            default:
                break;
        }
    }

    /***
     *单选dialog
     * @param dialogNum 3-线上线下/2-最新周···
     */
    private void showDialogSelect( final int dialogNum) {
        View view = LayoutInflater.from(NationalOverViewActivity.this).inflate(R.layout.dialog_single, null);
        dialog = new Dialog(NationalOverViewActivity.this, R.style.DialogBlack);
        Window window = dialog.getWindow();
        window.setContentView(view);
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.CENTER);

        final TextView dialog_title1 = (TextView) view.findViewById(R.id.dialog_title1);
        TextView dialog_title2 = (TextView) view.findViewById(R.id.dialog_title2);
        final WheelView wheelview_single1 = (WheelView) view.findViewById(R.id.wheelview_single1);
        final WheelView wheelview_single2 = (WheelView) view.findViewById(R.id.wheelview_single2);
        dialog_title2.setVisibility(View.GONE);
        wheelview_single2.setVisibility(View.GONE);
        wheelview_single1.setSkin(WheelView.Skin.None);
        WheelView.WheelViewStyle style = new WheelView.WheelViewStyle();
        style.selectedTextColor = Color.RED;
        style.selectedTextSize = 20;
        style.textColor = Color.BLACK;
        wheelview_single1.setStyle(style);
        wheelview_single1.setLoop(false);
        wheelview_single1.setWheelClickable(false);
        switch (dialogNum) {
            case 1:
                dialog_title1.setText("选择销量销额");
                wheelview_single1.setWheelData(sales);
                wheelview_single1.setSelection(getSelectPosition(sales, saleStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(this));
                break;
            case 2:
                dialog_title1.setText("选择周度时长");
                wheelview_single1.setWheelData(weeks);
                wheelview_single1.setSelection(getSelectPosition(weeks, weekStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(this));
                break;
            case 3:
                dialog_title1.setText("选择销售状况");
                wheelview_single1.setWheelData(dataMeasure);
                wheelview_single1.setSelection(getSelectPosition(dataMeasure, measureStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(this));
                break;
            default:
                break;
        }

        view.findViewById(dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });

        view.findViewById(R.id.dialog_ensure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (dialogNum) {
                    case 1:
                        saleStringTemp = sales.get(wheelview_single1.getCurrentPosition());
                        sale_text.setText(saleStringTemp);
                        if (sales.get(wheelview_single1.getCurrentPosition()).equals("销量")) {
                            saleStringTemp = "volume";
                            sale_text.setText("销量");
                            new SharedPreferencesUtils(NationalOverViewActivity.this).setSaleType(1);
                        } else {
                            saleStringTemp = "amount";
                            sale_text.setText("销额");
                            new SharedPreferencesUtils(NationalOverViewActivity.this).setSaleType(2);
                        }
                        break;
                    case 2:
                        weekStringTemp = weeks.get(wheelview_single1.getCurrentPosition());
                        week_text.setText(weekString);
                        switch (weekStringTemp){
                            case "近四周":
                                week_text.setText("近四周");
                                weekString = "fourWeek";
                                new SharedPreferencesUtils(NationalOverViewActivity.this).setWeekType("近四周");
                                break;
                            case "近八周":
                                week_text.setText("近八周");
                                weekString = "eightWeek";
                                new SharedPreferencesUtils(NationalOverViewActivity.this).setWeekType("近八周");
                                break;
                            case "本年累计":
                                week_text.setText("本年累计");
                                weekString = "year";
                                new SharedPreferencesUtils(NationalOverViewActivity.this).setWeekType("本年累计");
                                break;
                            case "当前周":
                                week_text.setText("当前周");
                                weekString = "current";
                                new SharedPreferencesUtils(NationalOverViewActivity.this).setWeekType("当前周");
                                break;
                            default:
                                week_text.setText("当前周");
                                weekString = "current";
                                new SharedPreferencesUtils(NationalOverViewActivity.this).setWeekType("当前周");
                                break;
                        }


                        break;
                    case 3:
                        measureStringTemp = dataMeasure.get(wheelview_single1.getCurrentPosition());
                        line_text.setText(measureString);
                        if (dataMeasure.get(wheelview_single1.getCurrentPosition()).equals("线上")) {
                            measureString = "online";
                            line_text.setText("线上");
                            new SharedPreferencesUtils(NationalOverViewActivity.this).setLineType(1);
                        } else {
                            measureString = "offline";
                            line_text.setText("线下");
                            new SharedPreferencesUtils(NationalOverViewActivity.this).setLineType(2);
                        }
                        break;
                }
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                getCompeting();
            }
        });
    }

    /***
     * 获取选择的索引
     * @param dataTemp
     * @param stringTemp
     * @return
     */
    private int getSelectPosition(ArrayList<String> dataTemp, String stringTemp) {
        int temp = 0;
        for (int i = 0; i < dataTemp.size(); i++) {
            if (dataTemp.get(i).equals(stringTemp)) {
                temp = i;
            }
        }
        return temp;
    }


    /***
     * 获取页面信息
     */
    private void getCompeting(){
        loading.setVisibility(View.VISIBLE);
        HashMap<String,Object> map =new HashMap<>();
        map.put("lastWeek", new SharedPreferencesUtils(this).getNewWeek());
        map.put("selfbrand","A.O.史密斯");
        ThreadPoolUtils.execute(new JsonRunnable(NationalOverViewActivity.this,"HTTPGET", AvcConstants.URLHeaderBase+AvcConstants.URL_CompetingBrand,handler,map,2));
    }

    /***
     * 获取页面信息
     */
    private void getCateSyncInfo1(){
        loading.setVisibility(View.VISIBLE);
        HashMap<String,Object> map =new HashMap<>();
        map.put("brand","A.O.史密斯");
        map.put("linesType",measureString);
        map.put("timeType",weekString);
        map.put("categorys","电储水热水器,燃气热水器,净水器,净化器");
        map.put("lastWeek", new SharedPreferencesUtils(this).getNewWeek());
        ThreadPoolUtils.execute(new JsonRunnable(NationalOverViewActivity.this,"HTTPGET",AvcConstants.URLHeaderBase+AvcConstants.URL_Synthesize,handler,map,1));
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case -1 :
                    loading.setVisibility(View.GONE);
                    break;
                case 1:
                    // TODO: 2017/9/13 页面完成，接口对接完成。由于登录失败，无法进行校验 
                    loading.setVisibility(View.GONE);
                    datas.clear();
                    CateSyncInfo csi = new Gson().fromJson(msg.obj.toString(),CateSyncInfo.class);
                    if(null == csi.getReturnValue() || "".equals(csi.getReturnValue())){

                    }else{
                        CateGroiseOverview cate0 = new CateGroiseOverview();
                        CateGroiseOverview cate1 = new CateGroiseOverview();
                        CateGroiseOverview cate2 = new CateGroiseOverview();
                        CateGroiseOverview cate3 = new CateGroiseOverview();
                        //净化器
                        if(csi.getReturnValue().get净化器().size()>0){
                            cate0.setCategory(csi.getReturnValue().get净化器().get(0).getCategory());
                            cate0.setBrand(csi.getReturnValue().get净化器().get(0).getBrand());
                            if(sale_text.getText().toString().equals("销额")){
                                cate0.setMarketShare(csi.getReturnValue().get净化器().get(0).getAmountMarketShare());
                                cate0.setMarketShareBasisRatio(csi.getReturnValue().get净化器().get(0).getAmountMarketShareBasisRatio());
                                cate0.setMarketShareLinkRelativeRatio(csi.getReturnValue().get净化器().get(0).getAmountMarketShareLinkRelativeRatio());
                            }else{
                                cate0.setMarketShare(csi.getReturnValue().get净化器().get(0).getVolumeMarketShare());
                                cate0.setMarketShareBasisRatio(csi.getReturnValue().get净化器().get(0).getVolumeMarketShareBasisRatio());
                                cate0.setMarketShareLinkRelativeRatio(csi.getReturnValue().get净化器().get(0).getVolumeMarketShareLinkRelativeRatio());
                            }
                        }
                        //净水器
                        if(csi.getReturnValue().get净水器().size()>0){
                            cate1.setCategory(csi.getReturnValue().get净水器().get(0).getCategory());
                            cate1.setBrand(csi.getReturnValue().get净水器().get(0).getBrand());
                            if(sale_text.getText().toString().equals("销额")){
                                cate1.setMarketShare(csi.getReturnValue().get净水器().get(0).getAmountMarketShare());
                                cate1.setMarketShareBasisRatio(csi.getReturnValue().get净水器().get(0).getAmountMarketShareBasisRatio());
                                cate1.setMarketShareLinkRelativeRatio(csi.getReturnValue().get净水器().get(0).getAmountMarketShareLinkRelativeRatio());
                            }else{
                                cate1.setMarketShare(csi.getReturnValue().get净水器().get(0).getVolumeMarketShare());
                                cate1.setMarketShareBasisRatio(csi.getReturnValue().get净水器().get(0).getVolumeMarketShareBasisRatio());
                                cate1.setMarketShareLinkRelativeRatio(csi.getReturnValue().get净水器().get(0).getVolumeMarketShareLinkRelativeRatio());
                            }
                        }
                        //燃气热水器
                        if(csi.getReturnValue().get燃气热水器().size()>0){
                            cate2.setCategory(csi.getReturnValue().get燃气热水器().get(0).getCategory());
                            cate2.setBrand(csi.getReturnValue().get燃气热水器().get(0).getBrand());
                            if(sale_text.getText().toString().equals("销额")){
                                cate2.setMarketShare(csi.getReturnValue().get燃气热水器().get(0).getAmountMarketShare());
                                cate2.setMarketShareBasisRatio(csi.getReturnValue().get燃气热水器().get(0).getAmountMarketShareBasisRatio());
                                cate2.setMarketShareLinkRelativeRatio(csi.getReturnValue().get燃气热水器().get(0).getAmountMarketShareLinkRelativeRatio());
                            }else{
                                cate2.setMarketShare(csi.getReturnValue().get燃气热水器().get(0).getVolumeMarketShare());
                                cate2.setMarketShareBasisRatio(csi.getReturnValue().get燃气热水器().get(0).getVolumeMarketShareBasisRatio());
                                cate2.setMarketShareLinkRelativeRatio(csi.getReturnValue().get燃气热水器().get(0).getVolumeMarketShareLinkRelativeRatio());
                            }
                        }
                        //电储水热水器
                        if(csi.getReturnValue().get电储水热水器().size()>0){
                            cate3.setCategory(csi.getReturnValue().get电储水热水器().get(0).getCategory());
                            cate3.setBrand(csi.getReturnValue().get电储水热水器().get(0).getBrand());
                            if(sale_text.getText().toString().equals("销额")){
                                cate3.setMarketShare(csi.getReturnValue().get电储水热水器().get(0).getAmountMarketShare());
                                cate3.setMarketShareBasisRatio(csi.getReturnValue().get电储水热水器().get(0).getAmountMarketShareBasisRatio());
                                cate3.setMarketShareLinkRelativeRatio(csi.getReturnValue().get电储水热水器().get(0).getAmountMarketShareLinkRelativeRatio());
                            }else{
                                cate3.setMarketShare(csi.getReturnValue().get电储水热水器().get(0).getVolumeMarketShare());
                                cate3.setMarketShareBasisRatio(csi.getReturnValue().get电储水热水器().get(0).getVolumeMarketShareBasisRatio());
                                cate3.setMarketShareLinkRelativeRatio(csi.getReturnValue().get电储水热水器().get(0).getVolumeMarketShareLinkRelativeRatio());
                            }
                        }
                        datas.add(cate3);
                        datas.add(cate2);
                        datas.add(cate1);
                        datas.add(cate0);

                    }
                    //刷新适配器
                    adapter.notifyDataSetChanged();
                    Log.e("????","数据解析");
                    if(weekString.equals("current")){
                        week_text.setText(csi.getMessage());
                    }
                    sp.setWeekType("当前周");
                    break;
                case 2:
                    boolean isSelected = false;
                    UserCompetingBrandInfo info  = new Gson().fromJson(msg.obj.toString(),UserCompetingBrandInfo.class);
                    StringBuffer sb = new StringBuffer();


//                    if(info.getReturnValue().get(0).getCompetingBrands().size() == 0 &&
//                            info.getReturnValue().get(1).getCompetingBrands().size() == 0 &&
//                            info.getReturnValue().get(2).getCompetingBrands().size() == 0 &&
//                            info.getReturnValue().get(3).getCompetingBrands().size() == 0 ){
//                        Intent intent1 = new Intent(NationalOverViewActivity.this, PersonalAttentionCategoryActivity.class);
//                        intent1.putExtra("where","login");
//                        startActivity(intent1);
//                    }else{
                    for(int i=0;i<info.getReturnValue().size();i++){
                        Set<String> brands = new HashSet();
                        for(int j=0;j<info.getReturnValue().get(i).getCompetingBrands().size();j++){
                            brands.add(info.getReturnValue().get(i).getCompetingBrands().get(j).trim());
                        }
                        new SharedPreferencesUtils(NationalOverViewActivity.this).setCompetingBrands(info.getReturnValue().get(i).getCategory(),brands);
                        if(info.getReturnValue().get(i).getCompetingBrands().size() !=0){
                            sb.append(info.getReturnValue().get(i).getCategory()+",");
                        }
//                        }
                        new SharedPreferencesUtils(NationalOverViewActivity.this).setCompetingCategory(sb.deleteCharAt(sb.length()-1).toString());
                        getCateSyncInfo1();
                    }
                    break;
                case -22:
                    loading.setVisibility(View.GONE);
                    Intent intent = new Intent ();
                    intent.setClass (NationalOverViewActivity.this, Login_Activity.class );
                    intent.setFlags ( Intent.FLAG_ACTIVITY_CLEAR_TASK );  //注意本行的FLAG设置
                    NationalOverViewActivity.this.finish ();
                    startActivity ( intent );
                    break;
                default:
                    break;
            }
        }
    };

    public class CateGroiseOverview{
        private String category;
        private String brand;
        private String MarketShare;
        private String MarketShareBasisRatio;
        private String MarketShareLinkRelativeRatio;

        public String getCategory() {
            return category;
        }

        public void setCategory(String category) {
            this.category = category;
        }

        public String getBrand() {
            return brand;
        }

        public void setBrand(String brand) {
            this.brand = brand;
        }

        public String getMarketShare() {
            return MarketShare;
        }

        public void setMarketShare(String marketShare) {
            MarketShare = marketShare;
        }

        public String getMarketShareBasisRatio() {
            return MarketShareBasisRatio;
        }

        public void setMarketShareBasisRatio(String marketShareBasisRatio) {
            MarketShareBasisRatio = marketShareBasisRatio;
        }

        public String getMarketShareLinkRelativeRatio() {
            return MarketShareLinkRelativeRatio;
        }

        public void setMarketShareLinkRelativeRatio(String marketShareLinkRelativeRatio) {
            MarketShareLinkRelativeRatio = marketShareLinkRelativeRatio;
        }
    }

}
